package bch.rocketmq.test;

import java.util.concurrent.Semaphore;

public class SemaphoreExample {
    private static final int THREAD_COUNT = 10;
    private static final Semaphore semaphore = new Semaphore(3); // 同时允许3个线程

    public static void main(String[] args) {
        for (int i = 1; i <= THREAD_COUNT; i++) {
            int threadId = i;
            new Thread(() -> {
                try {
                    System.out.println("Thread " + threadId + " waiting for permit");
                    semaphore.acquire();
                    System.out.println("Thread " + threadId + " acquired permit");
                    
                    // 模拟业务处理
                    Thread.sleep(2000);

                    System.out.println("Thread " + threadId + " releasing permit");
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
